#include <stdlib.h>
#include "shell.h"
#include "shell_cfg.h"
#include "py32f403xx_Start_Kit.h"

int reboot(int argc, char *agrv[])
{
  printf(" %dparameter(s)\r\n", argc);
  for (char i = 1; i < argc; i++)
  {
    printf("%s\r\n", agrv[i]);
  }
  NVIC_SystemReset();
  //return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN), reboot, reboot, reboot);

int led(int argc, char *agrv[])
{
  uint32_t temp, rtn, i;
  if(argc == 2) {
    rtn = sscanf(agrv[1],"%d", &temp);
    if(rtn == 1) {
      if(temp == 0) {
        BSP_LED_Off(LED3);
        printf("LED3 is off!\r\n");
      } else if(temp == 1) {
        BSP_LED_On(LED3);
        printf("LED3 is on!\r\n");
      } else if(temp == 2) {
        BSP_LED_Toggle(LED3);
        printf("LED3 is toggled!\r\n");
      } else if(temp == 3) {
        for(i = 0; i < 6; i++) {
          BSP_LED_Toggle(LED3);
          HAL_Delay(400); // cannot be used in interrupt.
        }
        printf("LED is blinked!\r\n");
      }
    }
  }
  return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN)|SHELL_CMD_DISABLE_RETURN, led, led, led);

int rand_data(int argc, char *agrv[])
{
  srand(HAL_GetTick());
  printf("Randon Data = 0x%08x\r\n", rand());
  return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN)|SHELL_CMD_DISABLE_RETURN, rand_data, rand_data, rand_data);

int mdb(int argc, char *agrv[])
{
  uint32_t addr, size, rtn, i;
  if(argc == 3) {
    rtn = sscanf(agrv[1],"%x", &addr);
    if(rtn != 1) {
      printf("get addr error!\r\n");
    }
    rtn = sscanf(agrv[2],"%x", &size);
    if(rtn != 1) {
      printf("get size error!\r\n");
    }
    for (i=0; i<size; i++)
    {
      if (0 == (i%0x10))
      {
        printf("\r\n0x%08X:", addr+i);
      }
      printf(" %02X", HW8_REG(addr+i));
    }
  }
  return 0;
}
SHELL_EXPORT_CMD(SHELL_CMD_PERMISSION(0)|SHELL_CMD_TYPE(SHELL_TYPE_CMD_MAIN)|SHELL_CMD_DISABLE_RETURN, mdb, mdb, mdb);
